<?php

namespace common\models\user;

use common\models\actor\Actor;
use Yii;
use common\helpers\Url;
use common\helpers\ArrayHelper;
use common\helpers\StringHelper;
use common\models\member\Member;
use common\models\user\UserAccount;

/**
 * This is the model class for table "{{%user}}".
 *
 * @property int $id 用户ID
 * @property int $original_user_id
 * @property string $username 用户名
 * @property string $nickname 昵称
 * @property string $avatar 头像
 * @property string $mobile 手机号
 * @property string $mobile_hash 手机号（加密）
 * @property string $email 邮箱
 * @property string $auth_key 加密密钥
 * @property string $password_hash HASH密码
 * @property string $password_reset_token 重置密码时效Token
 * @property int $ip 注册IP
 * @property int $status 状态
 * @property int $created_at 注册时间
 * @property int $updated_at 更新时间
 * @property int $deleted_at 注销时间
 */
class User extends \common\base\User {

    use \common\traits\Constants;

    const STATUS_DELETED = -1;
    const STATUS_DEFAULT = 0;
    const STATUS_ACTIVE = 10;

    /**
     * {@inheritdoc}
     */
    public static function tableName() {
        return '{{%user}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return [
            [['original_user_id', 'ip', 'status', 'created_at', 'updated_at', 'deleted_at'], 'integer'],
            [['username', 'auth_key'], 'required'],
            [['username', 'nickname', 'mobile', 'auth_key'], 'string', 'max' => 32],
            [['avatar', 'mobile_hash', 'password_hash', 'password_reset_token'], 'string', 'max' => 255],
            [['email'], 'string', 'max' => 50],
            [['username'], 'unique'],
            [['mobile'], 'unique'],
            [['password_reset_token'], 'unique'],
            [['email'], 'unique'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels() {
        return [
            'id' => '用户ID',
            'original_user_id' => 'Original User ID',
            'username' => '用户名',
            'nickname' => '昵称',
            'avatar' => '头像',
            'mobile' => '手机号',
            'mobile_hash' => '手机号（加密）',
            'email' => '邮箱',
            'auth_key' => '加密密钥',
            'password_hash' => 'HASH密码',
            'password_reset_token' => '重置密码时效Token',
            'ip' => '注册IP',
            'status' => '状态',
            'created_at' => '注册时间',
            'updated_at' => '更新时间',
            'deleted_at' => '注销时间',
        ];
    }

    public function getPortrait() {
        return Url::attach($this->avatar);
    }

    public function getUserName() {
        if ($this->nickname) {
            return $this->nickname;
        }
        return $this->username;
    }

    /**
     * 返回可用于检查给定身份ID的有效性的密钥
     *
     * @inheritdoc
     */
    public function getExtends() {
        if ($this->avalidMember) {
            return $this->avalidMember->type->name;
        }
        return '普通用户';
    }

    /**
     * 返回可用于检查给定身份ID的有效性的密钥
     *
     * @inheritdoc
     */
    public function getUserType() {
        if ($this->avalidMember) {
            return $this->avalidMember->type->name;
        }
        return '普通用户';
    }

    public function getMeta() {
        return $this->hasOne(UserMeta::className(), ['id' => 'id']);
    }

    public function getMember() {
        return $this->hasOne(Member::class, ['user_id' => 'id']);
    }

    public function getAccount() {
        return $this->hasOne(UserAccount::class, ['user_id' => 'id'])->andWhere([
            'type' => UserAccount::TYPE_CREDIT
        ]);
    }

    public function getMemberAccount() {
        return $this->hasOne(\common\models\member\MemberAccount::class, ['user_id' => 'id']);
    }

    public function getActor() {
        return $this->hasOne(Actor::class, ['user_id' => 'id']);
    }

    /**
     * 获取会员信息
     *
     * @return type
     */
    public function getAvalidMember() {
        return $this->getMember()->active(Member::STATUS_ACTIVE)->andWhere([
            'audit_status' => Member::AUDIT_STATUS_FINISH,
        ])->andWhere([
            'or',
            ['expired_at' => 0],
            ['>', 'expired_at', time()],
        ]);
    }

    public function getAgent() {
        return $this->hasOne(UserBranch::className(), ['user_id' => 'id'])->andWhere([
            '!=', 'member_user_id', $this->id
        ]);
    }

    public function getMineAgent() {
        return $this->hasOne(UserBranch::className(), ['user_id' => 'id']);
    }

    public function getIm() {
        return $this->hasOne(UserIm::class, ['user_id' => 'id']);
    }

    public function canJoinBranch() {
        if ($this->mineAgent) {
            return false;
        }
        return true;
    }

    /**
     * 解密手机号
     *
     * @param boolean $mask
     * @return string 手机号
     */
    public function getDecodeMobile($mask = true) {
        $mobile = Yii::$app->security->decryptMaster($this->mobile_hash);
        if ($mask !== false) {
            return StringHelper::maskChar($mobile, 3, 2);
        }
        return $mobile;
    }

    /**
     * @inheritdoc
     */
    public function setAvatar($avatar = null) {
        if ($avatar === null) {
            $avatar = ArrayHelper::getValue(Yii::$app->params, 'defaultImages.user_avatar');
        }
        $this->avatar = $avatar;
    }

    public function fields() {
        return [
            'id',
            'nickname' => 'userName',
            'portraitUri' => 'portrait',
            'avatar' => function () {
                return $this->avatar;
            },
            'token' => function () {
                return $this->im ? $this->im->im_token : '';
            }
        ];
    }

}
